package com.sj.security;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import com.sj.common.lang.ApiResultMsg;
import com.sj.entity.User;
import com.sj.service.UserService;
import com.sj.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: xiaoqi
 * Date: 2021-08-02
 * Time: 上午 11:58
 * Description: security登录成功处理器
 *
 * @author xiaoqi
 */

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private UserService userService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();

        String token = jwtUtils.generateToken(authentication.getName());
        response.setHeader(jwtUtils.getHeader(), token);

        User userInfo = userService.getUserByUsername(authentication.getName());
        userInfo.setPassword(null);
        userInfo.setStatus(null);
        // 生成jwt
        ApiResultMsg resultMsg = ApiResultMsg.success("登录成功",
                MapUtil.builder()
                        .put("token", token)
                        .put("userInfo", userInfo)
                        .build()
        );
        outputStream.write(JSONUtil.toJsonStr(resultMsg).getBytes("UTF-8"));
        outputStream.flush();
        outputStream.close();
    }
}